package com.qn.sms.core.client.impl;

import com.qn.sms.core.client.SmsClient;
import com.qn.sms.core.client.SmsClientFactory;
import com.qn.sms.core.client.aliyun.AliyunSmsClient;
import com.qn.sms.core.enums.SmsChannelEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 短信客户端工厂接口
 *
 * @author QN
 * @date 2022/03/03
 */
@Slf4j
public class SmsClientFactoryImpl implements SmsClientFactory {

    /**
     * 短信客户端 Map
     * key：渠道编码
     *
     * 注意，一些场景下，需要获得某个渠道类型的客户端，所以需要使用它。
     * 例如说，解析短信接收结果，是相对通用的，不需要使用某个渠道编号的
     */
    private final ConcurrentMap<String, AbstractSmsClient> channelCodeClients = new ConcurrentHashMap<>();

    @Override
    public SmsClient getSmsClient(SmsChannelEnum smsChannelEnum) {
        return channelCodeClients.get(smsChannelEnum.getCode());
    }

    @Override
    public void createOrUpdateSmsClient(SmsChannelEnum smsChannelEnum) {
        String code = smsChannelEnum.getCode();
        AbstractSmsClient client = channelCodeClients.get(code);
        if (client == null) {
            client = this.createSmsClient(smsChannelEnum);
            client.init();
            channelCodeClients.put(code, client);
        }
    }

    private AbstractSmsClient createSmsClient(SmsChannelEnum channelEnum) {
        Assert.notNull(channelEnum, String.format("渠道类型(%s) 为空", channelEnum));
        // 创建客户端
        switch (channelEnum) {
            case ALIYUN:
                return new AliyunSmsClient();
        }
        // 创建失败，错误日志 + 抛出异常
        log.error("[createSmsClient] 找不到合适的客户端实现]");
        throw new IllegalArgumentException("找不到合适的客户端实现");
    }
}
